<template>
  <div class="user_home_container padd100">
    <el-row :gutter="20">
      <el-col>
        <!--用户信息 -->
        <div class="user_info_wrapper">
          <div class="left_user_avatar">
            <img :src="userInfo.profile.avatarUrl + '?param=180y180'" alt="">
          </div>
          <div class="right_user_info">
            <div class="user_name">
              <div class="left_name">
                {{userInfo.profile.nickname}}
              </div>
              <div class="level">
                <el-tag round>Lv.{{userInfo.level}}</el-tag>
              </div>
              <div class="sex_img">
                <img :src="userInfo.profile.gender === 1? manImg:womanImg" alt="">
              </div>
              <!-- <div class="btn_group" v-if="localUserInfo.userId != uid">
                <el-button :icon="Promotion">发私信</el-button>
                <el-button type="primary" :icon="Plus">关注</el-button>
              </div> -->
            </div>
            <div class="user_data">
              <div class="data_item">
                <div class="top_num">{{userInfo.profile.eventCount}}</div>
                <div class="bottom_desc">动态</div>
              </div>
              <div class="data_item">
                <div class="top_num">{{userInfo.profile.follows}}</div>
                <div class="bottom_desc">关注</div>
              </div>
              <div class="data_item">
                <div class="top_num">{{userInfo.profile.followeds}}</div>
                <div class="bottom_desc">粉丝</div>
              </div>
            </div>
            <div class="user_ohter_info">
              <div class="ohter_info_item" v-if="userInfo.profile.description">
                <span>个人介绍：</span>
                <span>{{userInfo.profile.description}}</span>
              </div>
              <div class="ohter_info_item">
                <span>所在地区：</span>
                <span>{{provienceAndCity.pro}} - {{provienceAndCity.cit}}</span>
              </div>
              <!-- <div class="ohter_info_item">
                <span>社交网络：</span>
                <span>Carpe diem | 工作請洽：水晶共振經紀公司 TEL : (+886 2) 2752 1665 Email: crystalresonance2010@gmail.com</span>
              </div> -->
            </div>
          </div>
        </div>
        <!-- 表格 -->
        <div class="music_listen_wrppaer" v-if="localUserInfo.userId === uid">
          <div class="top_b_m_tit">
            <div class="left_tit">
              <div>听歌排行</div>
              <span>累积听歌{{userInfo.listenSongs}}首</span>
            </div>
            <div class="right_play_count">
              <el-button link :style="{'font-weight':recordType===1?'700':'normal'}" @click="handleClickChangeTime(1)">
                最近一周</el-button>
              <span style="margin:0 10px;">|</span>
              <el-button link :style="{'font-weight':recordType===2?'700':'normal'}" @click="handleClickChangeTime(2)">
                所有时间</el-button>
            </div>
          </div>
          <div>
            <MusicTable :tracks="listMusicTop" />
          </div>
          <!-- <div class="pageination_center" style="margin-top:10px">
            <el-button link>查看更多 ></el-button>
          </div> -->
        </div>
        <!-- 动态 & 关注 & 粉丝 -->
        <div class="my_user_data_wrapper">
          <el-tabs type="border-card" v-model="activeName">
            <el-tab-pane :label="`动态（${userInfo.profile.eventCount}）`" name="first">
              <el-scrollbar class="event" max-height="800px">
                <div v-infinite-scroll="scrollbottom" infinite-scroll-distance="200">
                  <event v-for="(item, index) in eventData.events" :item="item" @getData="getEvent(true)" />
                </div>
              </el-scrollbar>
            </el-tab-pane>
            <el-tab-pane :label="`关注（${userInfo.profile.follows}）`" name="second">
              <div class="panel">
                <el-row :gutter="20">
                  <el-col :lg="12" :md="12" v-for="item in follows.list" style="margin-bottom:20px">
                    <Follow :item="item" />
                  </el-col>
                </el-row>
                <div class="pageination_center" style="margin-top:40px">
                  <el-pagination v-show="userInfo.profile.follows > followsPage.pageSize"
                    v-model:currentPage="followsPage.pageNum" :page-size="followsPage.pageSize" background
                    layout="prev, pager, next" :total="userInfo.profile.follows" @update:current-page="getFollows()" />
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane :label="`粉丝（${userInfo.profile.followeds}）`" name="third">
              <div class="panel">
                <el-row :gutter="20">
                  <el-col :lg="12" :md="12" v-for="item in followeds.list" style="margin-bottom:20px">
                    <Follow :item="item" />
                  </el-col>
                </el-row>
                <div class="pageination_center" style="margin-top:40px">
                  <el-pagination v-show="userInfo.profile.followeds > followedsPage.pageSize"
                    v-model:currentPage="followedsPage.pageNum" :page-size="followedsPage.pageSize" background
                    layout="prev, pager, next" :total="userInfo.profile.followeds"
                    @update:current-page="getFolloweds()" />
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <!-- 创建的歌单 -->
        <div class="my_music_list">
          <div class="top_b_m_tit">
            <div class="left_tit">
              <div><template v-if="localUserInfo.userId == uid">我</template><template v-else><template
                    v-if="userInfo.profile.gender === 1">他</template><template v-else>她</template></template>创建的歌单
                ({{myPlaylistData.length}})</div>
            </div>
          </div>
          <div class="music_list_wrapper">
            <el-row :gutter="20">
              <el-col :lg="3" :md="4" :sm="6" :xs="12" v-for="item in myPlaylistData" :key="item"
                style="margin-bottom:20px">
                <MusicHead :authorInfo="false" :name="item.name" :id="item.id" :coverImgUrl="item.coverImgUrl"
                  :playCount="item.playCount"
                  @handleClickToListDetail="(id:number)=>{router.push({name:'play-list-detail',params:{id}})}" />
              </el-col>
            </el-row>
          </div>
        </div>
        <!-- 我收藏的歌单 -->
        <div class="my_music_star_list">
          <div class="top_b_m_tit">
            <div class="left_tit">
              <div><template v-if="localUserInfo.userId == uid">我</template><template v-else><template
                    v-if="userInfo.profile.gender === 1">他</template><template v-else>她</template></template>收藏的歌单
                ({{myCollectionlistData.length}})</div>
            </div>
          </div>
          <div class="music_list_wrapper">
            <el-row :gutter="20">
              <el-col :lg="3" :md="4" :sm="6" :xs="12" v-for="item in myCollectionlistData" :key="item"
                style="margin-bottom:20px">
                <MusicHead :authorInfo="false" :name="item.name" :id="item.id" :coverImgUrl="item.coverImgUrl"
                  :playCount="item.playCount"
                  @handleClickToListDetail="(id:number)=>{router.push({name:'play-list-detail',params:{id}})}" />
              </el-col>
            </el-row>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script lang="ts" setup>
import { Headset, VideoPlay, FolderAdd, Plus, Pointer, Promotion } from '@element-plus/icons-vue'
import MusicHead from "@/components/MusicHead/index";
import { getCurrentInstance, reactive, ref, toRefs, watch, onMounted } from "vue"
import Follow from "@/components/Follow/index";
import MusicTable from "@/components/MusicTable";
import event from "@/components/Event/index"
import { detail, getUserRecord } from "@/api/userinfo";
import type { TabsPaneContext } from 'element-plus'
import * as userApi from '@/api/userinfo'
import router from '@/router';
import { useRoute } from "vue-router";
import { ElMessage } from 'element-plus';
import { playlist } from "@/api/my-music";
const cityJson = require('../../assets/city.json');
const { proxy }: any = getCurrentInstance()
const manImg = require('../../assets/images/man.png')
const womanImg = require('../../assets/images/woman.png')
const recordType = ref<number>(1)
const listMusicTop = ref<any>([])
const route = useRoute()
// 我创建的歌单
const myPlaylistData = ref<any>([])
// 我收藏的歌单
const myCollectionlistData = ref<any>([])
// 路由参数
let uid = route.params.id
const activeName = ref<any>('first')
// 所在地区
const provienceAndCity = reactive({
  pro: '',
  cit: ''
})
const eventData = reactive<any>({
  lasttime: -1,
  events: [],
  more: true,
})
const followsPage = reactive({
  pageNum: 1, // 当前页数
  pageSize: 20 // 每页显示多少条
})
const follows = reactive({
  list: [],
  more: true
})
const followedsPage = reactive({
  pageNum: 1, // 当前页数
  pageSize: 20 // 每页显示多少条
})
const followeds = reactive({
  list: [],
  more: true
})
let localUserInfo = proxy.$getUserInfo()
const userInfo = ref<any>({ bindings: [{}], profile: {}, userPoint: {} })
// 获取用户详情信息
const getUserDetailData = async () => {
  const res: any = await detail({
    uid
  })
  userInfo.value = res
  let resObj = getCityData(userInfo.value.profile.province, userInfo.value.profile.city)
  provienceAndCity.pro = resObj.pro
  provienceAndCity.cit = resObj.cit
}
/**
 * 获取对应省，城市
 */
const getCityData = (province: number, city: number) => {
  // 省份
  let pro = ''
  // 城市
  let cit = ''
  for (const key in cityJson) {
    // console.log(key,":",cityJson[key]);
    if (Number(key) === province) {
      pro = cityJson[key]
    }
    if (Number(key) === city) {
      cit = cityJson[key]
    }
  }
  // console.log(pro,cit);
  return {
    pro,
    cit
  }
}
// 获取用户播放记录
const getUserRecordData = async () => {
  if (localUserInfo.userId === uid) {
    let cookie = localStorage.getItem('cookie')
    const res: any = await getUserRecord({
      uid,
      type: recordType.value,
      cookie
    })
    console.log(recordType.value);

    console.log(res);
    let arr: any[] = []
    if (recordType.value === 1) {
      res.weekData.forEach((item: { song: any; }) => {
        arr.push(item.song)
      })
    } else {
      // 傻逼接口没数据😁
      // res.allData.forEach((item: { song: any; }) => {
      //   arr.push(item.song)
      // })
    }
    listMusicTop.value = arr
  }
}
const handleClickChangeTime = (num: number) => {
  recordType.value = num
  getUserRecordData()
}
const getPlayListData = async () => {
  let cookie = localStorage.getItem('cookie')
  const res: any = await playlist({ uid, cookie })
  let myPlayList: any[] = []
  let myCollectPlayList: any[] = []
  res.playlist.forEach((item: { userId: any; }) => {
    if (item.userId == uid) {
      myPlayList.push(item)
    } else {
      myCollectPlayList.push(item)
    }
  })
  myPlaylistData.value = myPlayList
  myCollectionlistData.value = myCollectPlayList
}
const scrollbottom = () => {
  if (eventData.more) {
    eventData.more = false // 防止触发多次
    getEvent()
  }
}
const getEvent = async (isFrist: Boolean = false) => {
  try {
    // 是否重新请求
    if (isFrist) {
      eventData.lasttime = -1
      eventData.events = []
      eventData.more = true
    }
    const data: any = await userApi.event({ limit: 20, uid, lasttime: eventData.lasttime })
    eventData.lasttime = data.lasttime
    eventData.more = data.more
    data.events.forEach((item: any) => {
      item.json = JSON.parse(item.json)
      item.commentVisible = false
      // 转发
      if (item.json.event) {
        item.json.event.json = JSON.parse(item.json.event.json)
        item.json.event.commentVisible = false
      }
    });
    eventData.events = [...eventData.events, ...data.events]
  } catch (error) {
    console.log(error);
  }
}
const getFollows = async () => {
  try {
    const data: any = await userApi.follows({ limit: followsPage.pageSize, uid, offset: (followsPage.pageNum - 1) * followsPage.pageSize })
    follows.list = data.follow
    follows.more = data.more
  } catch (error) {
    console.log(error);
  }
}
const getFolloweds = async () => {
  try {
    const data: any = await userApi.followeds({ limit: followedsPage.pageSize, uid, offset: (followedsPage.pageNum - 1) * followedsPage.pageSize })
    followeds.list = data.followeds
    followeds.more = data.more
  } catch (error) {
    console.log(error);
  }
}
watch(() => router.currentRoute.value.path, (newValue, oldValue) => {
  console.log('路由变化了哦');
  // location.reload()
  uid = route.params.id
  if (uid && router.currentRoute.value.name === 'user-home') {
    getUserDetailData()
    getUserRecordData()
    getPlayListData()
    getEvent(true)
    getFollows()
    getFolloweds()
  }
})
if (uid) {
  getUserDetailData()
  getUserRecordData()
  getPlayListData()
  getEvent()
  getFollows()
  getFolloweds()
} else {
  ElMessage({
    message: "参数错误",
    type: 'error',
    duration: 2000,
    onClose: () => {
      history.go(-1)
    }
  })
}
onMounted(() => {
  activeName.value = route.query.activeName || "first"
})
</script>
<style lang="scss" scoped>
.user_home_container {
  margin-top: 20px;

  .user_info_wrapper {
    display: flex;
    flex-wrap: wrap;

    .left_user_avatar {
      width: 188px;
      height: 188px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .right_user_info {
      flex: 1;
      padding-left: 40px;

      .user_name {
        display: flex;
        align-items: center;
        border-bottom: 1px solid #ddd;
        padding-bottom: 20px;

        .left_name {
          font-size: 22px;
        }

        .level {
          margin-left: 8px;
        }

        .sex_img {
          width: 25px;
          margin-left: 8px;

          img {
            width: 100%;
          }
        }

        .btn_group {
          margin-left: 20px;
        }
      }

      .user_data {
        display: flex;
        margin-top: 10px;

        .data_item {
          display: flex;
          flex-direction: column;
          align-items: center;
          border-right: 1px solid #ddd;
          padding: 0 30px;

          &:last-child {
            border-right: 0;
          }

          &:first-child {
            padding-left: 0;
          }

          .top_num {
            color: #999;
            font-size: 24px;
            margin-bottom: 4px;
          }

          .bottom_desc {
            color: #666;
            font-size: 12px;
          }
        }
      }

      .user_ohter_info {
        margin-top: 20px;

        .ohter_info_item {
          font-size: 12px;
          color: #666;
          margin-bottom: 6px;

          span {
            line-height: 1.8;
          }
        }
      }
    }
  }

  .music_listen_wrppaer {
    margin: 30px 0;
  }

  .my_music_list {}

  .music_list_wrapper {
    padding: 20px 0;
  }

  .my_user_data_wrapper {
    margin: 30px 0;

    .event {
      width: 100%;
      padding: 0 10px;
      box-sizing: border-box;
    }

    .panel {
      padding: 20px 0;
    }
  }
}

.top_b_m_tit {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;

  .left_tit {
    color: #333;
    font-size: 20px;
    display: flex;

    span {
      color: #666;
      font-size: 12px;
      margin-top: 10px;
      margin-left: 14px;
    }
  }

  .right_play_count {
    span {
      color: #666;
      font-size: 12px;

      span {
        color: #409eff;
        font-weight: 700;
      }
    }
  }
}

:deep(.el-pagination) {
  display: flex;
  justify-content: center;
}
</style>
